package com.frxuexi.shop2307.user

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.CodeBean
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.lib_base.utils.LiveDataBus
import com.frxuexi.shop2307.R
import com.frxuexi.shop2307.databinding.ActivityLoginBinding
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask

@Route(path = "/app/LoginActivity")
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding,UserViewModel>() {

    var timer:Timer?=null
    var num=10

    @Autowired
    lateinit var user:String

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initData() {
        vm.codeData.observe(this){
            val codeBean = Gson().fromJson<CodeBean>(it.content, CodeBean::class.java)
            ToastUtils.showLong(codeBean.code)

            val manager = getSystemService(NotificationManager::class.java)
            val channel =
                NotificationChannel("not", "验证码", NotificationManager.IMPORTANCE_LOW)
            manager.createNotificationChannel(channel)

            //点击通知跳转
            val intent = Intent(this, CodeActivity::class.java)
            intent.putExtra("phone",binding.loginPhone.text.toString())
            intent.putExtra("code",codeBean.code)

            val pendingIntent = PendingIntent.getActivity(
                this, 101, intent,
                PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
            )

            val notification = Notification.Builder(this, "not")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("验证码")
                .setContentText("验证码是：${codeBean.code}")
                .setContentIntent(pendingIntent)
                .build()
            manager.notify(1,notification)
        }

        vm.loginData.observe(this){
            Log.i("lr",it.toString())
            ToastUtils.showLong("登录成功")
            SPUtils.getInstance().put(Const.TOKEN,it.token)
            SPUtils.getInstance().put(Const.PHONE,it.phone)
            SPUtils.getInstance().put(Const.UID,it.uid)

            vm.loginRoom(it)

        }

        vm.loginError.observe(this){
            ToastUtils.showLong(it)
        }

        vm.loginRoomData.observe(this){
            if(it>0){
                Log.i("lr","room新增user成功${it}")
                ARouter.getInstance().build("/app/MainActivity").navigation()
                finish()
            }
        }
    }

    override fun initView() {
        if(SPUtils.getInstance().getString(Const.TOKEN,"").isNotEmpty()){
            ARouter.getInstance().build("/app/MainActivity").navigation()
            finish()
        }


        binding.loginSendCode.setOnClickListener {
            val phone = binding.loginPhone.text.toString()
            if(phone.isNullOrEmpty()){
                ToastUtils.showLong("手机号不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileSimple(phone)){
                ToastUtils.showLong("不是合法手机号")
                return@setOnClickListener
            }
            binding.loginSendCode.isEnabled=false
            lifecycleScope.launch(Dispatchers.IO) {
                timer= Timer()
                timer!!.schedule(timerTask {
                    lifecycleScope.launch (Dispatchers.Main){
                        binding.loginSendCode.setText("还剩 ${num--}s")
                        if(num==0){
                            timer!!.cancel()
                            binding.loginSendCode.isEnabled=true
                            binding.loginSendCode.setText("重新发送")
                            num=10
                        }
                    }
                },0,1000)
            }
            vm.sendCode(phone)
            //6位随机数
//            val random = (1..1000000 - 1).random()
        }

        binding.loginBtn.setOnClickListener {
            val phone = binding.loginPhone.text.toString()
            val code = binding.loginCode.text.toString()
            val map = mapOf<String, Any>("phone" to phone, "captcha" to code)
            vm.login(map)
        }

        binding.loginCode.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if(s.isNullOrEmpty()){
                    binding.loginBtn.isEnabled=false
                }else{
                    binding.loginBtn.isEnabled=true
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        binding.loginRegister.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
        }

        binding.loginForget.setOnClickListener{

        }


        /*LiveDataBus.with("user",String::class.java).observe(this){
            val split = it.split(",")
            binding.loginPhone.setText(split[0])
            binding.loginCode.setText(split[1])
        }*/
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        ARouter.getInstance().inject(this)
//        val split = user.split(",")
        binding.loginPhone.setText(user)
//        binding.loginCode.setText(split[1])
    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
        timer=null
    }

}